package com.zlht.controller;

import com.zlht.entity.Store;
import com.zlht.service.EmployeeService;
import com.zlht.service.StoreService;
import com.zlht.service.imp.EmployeeServiceImp;
import com.zlht.service.imp.StoreServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/store")
public class StoreServlet extends HttpServlet {

    private StoreService storeService = new StoreServiceImp();
    private EmployeeService employeeService = new EmployeeServiceImp();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        switch (method) {
            case "list":
                req.setAttribute("list", this.storeService.list());
                req.setAttribute("employeeList",this.employeeService.list());
                req.getRequestDispatcher("adminmanager.jsp").forward(req, resp);
                break;
            case "search":
                String key = req.getParameter("key");
                String value = req.getParameter("value");
                req.setAttribute("list",this.storeService.search(key ,value));
                req.getRequestDispatcher("adminmanager.jsp").forward(req, resp);
                break;
            case "save":
                String name = req.getParameter("name");
                String adminName = req.getParameter("adminName");
                String phone = req.getParameter("phone");
                String location = req.getParameter("location");
                this.storeService.save(new Store(name,adminName,phone,location));
                resp.sendRedirect("/store?method=list");
                break;
            case "update":
                String idStr = req.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                name = req.getParameter("name");
                adminName = req.getParameter("adminName");
                phone = req.getParameter("phone");
                location = req.getParameter("location");
                this.storeService.update(new Store(id,name,adminName,phone,location));
                resp.sendRedirect("/store?method=list");
                break;
            case "delete":
                idStr = req.getParameter("id");
                id = Integer.parseInt(idStr);
                this.storeService.delete(id);
                resp.sendRedirect("/store?method=list");
                break;
                }
        }

}